package com.demo.account_service.application.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.demo.account_service.model.Account;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import com.demo.account_service.repository.accountRepository;
import com.demo.account_service.application.dto.AccountInDto;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

@Service
@AllArgsConstructor
public class AccountService {
    private final accountRepository accountRepository;

    //通过读入的账号信息去查询数据库
    public boolean checkAccount(AccountInDto accountInDto) {
        //空值判断
        Objects.requireNonNull(accountInDto, "accountInDto cannot be null");
        //通过账号检索数据库
        Wrapper<Account> query= Wrappers.<Account>lambdaQuery().eq(Account::getAccount_number, accountInDto.getAccount_number());
        Account account = accountRepository.selectByAccountNumber(query);
        //判断账号是否存在
        if (account == null) {
            return false;
        }
        //判断密码是否正确
        try {
            //创建MessageDigest对象
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            //应用SHA-256算法
            byte[] hash = digest.digest(accountInDto.getPassword().getBytes());
            //转化为16进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                hexString.append(String.format("%02X", b));
            }
            System.out.println("hexString: " + hexString.toString());
            return hexString.toString().equals(account.getPassword());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return false;
    }
}
